package frames;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/** Implements the tree popup menu for the
 * database system
 * 
 * @author Konstantin Dobrev
 * @version 1.0
 */
public class DBMSMenu extends JPopupMenu {

	private DatabaseTree dbTree;
	private Connection dbConnection;
	
	/** Class constructor
	 * 
	 * @param tree represents the database system tree
	 * @param connection represents the established connection
	 */
	DBMSMenu(DatabaseTree tree, Connection connection) {
		
		dbTree = tree;
		dbConnection = connection;
		
		JMenuItem createDBItem = new JMenuItem("Create a database");
		createDBItem.addActionListener(new DBMSMenuHandler());
		this.add(createDBItem);
	}
	
	/** Implements a listener for the database system menu options
	 * 
	 * @author Konstantin Dobrev
	 * @version 1.0
	 */
	private class DBMSMenuHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			String dbName = JOptionPane.showInputDialog(null, "Enter a name for the new database");
			try {
				Statement stm = dbConnection.createStatement();
				stm.execute("CREATE DATABASE " + dbName);
				DefaultTreeModel model = (DefaultTreeModel) dbTree.getModel();
				DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(dbName);
				DefaultMutableTreeNode root = (DefaultMutableTreeNode) dbTree.getModel().getRoot();
				model.insertNodeInto(newNode, root, 0);
			} catch (SQLException ex) {
				JOptionPane.showMessageDialog(null, ex.getMessage());
			}
		}
		
	}
	
}
